package com.atguigu.base;

import java.sql.*;
import java.util.Scanner;

/**
 * @author lhl
 * @date 2025/4/11 17:00
 */
public class JDBCPrepared {
    public static void main(String[] args) throws Exception {
        //1.注册驱动
        //Class.forName("com.mysql.cj.jdbc.Driver");
        //DriverManager.registerDriver(new Driver());

        //2.获取连接对象
        String url = "jdbc:mysql://localhost:3306/atguigu";
        String username = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, username, password);

        //3.获取执行SQL语句的对象
        PreparedStatement preparedStatement = connection.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_emp where emp_name = ?");

        System.out.println("请输入员工姓名");
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();  //abc' or '1' = '1

        //4.为？占位符设置值，并执行,接收返回结果集
        preparedStatement.setString(1,name);
        ResultSet resultSet = preparedStatement.executeQuery();

        //5.处理结果集
        while (resultSet.next()){
            int empId = resultSet.getInt("emp_id");
            String empName = resultSet.getString("emp_name");
            Double empSalary = resultSet.getDouble("emp_salary");
            int empAge = resultSet.getInt("emp_age");

            System.out.println("emp_id："+empId+"\t"+"emp_name："+empName+"\t"+"emp_salary："+empSalary+"\t"+"emp_age："+empAge+"\t");
        }

        //6.释放资源（先开后关）
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
